package org.zebra.file.excel.core;

import cn.hutool.core.util.StrUtil;
import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.event.AnalysisEventListener;
import cn.idev.excel.exception.ExcelDataConvertException;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Excel 导入监听
 *
 * @author zhanghongbin
 */
@Slf4j
public abstract class ExcelListener<T> extends AnalysisEventListener<T> {

    /**
     * 是否Validator检验
     */
    protected Boolean isValidate;

    /**
     * 导入回执
     */
    protected ExcelResult<T> excelResult;
    /**
     * excel 表头数据
     */
    private Map<Integer, String> headMap;

    public ExcelListener(Boolean isValidate) {
        this.isValidate = isValidate;
        this.excelResult = new ExcelResult<>();
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.headMap = headMap;
    }

    /**
     * 处理异常
     *
     * @param exception ExcelDataConvertException
     * @param context   Excel 上下文
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        String errMsg = null;
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            // 如果是某一个单元格的转换异常 能获取到具体行号
            Integer rowIndex = excelDataConvertException.getRowIndex();
            Integer columnIndex = excelDataConvertException.getColumnIndex();
            errMsg = StrUtil.format(
                    "第{}行-第{}列-表头{}: 解析异常<br/>", rowIndex + 1, columnIndex + 1, headMap.get(columnIndex));
            log.error(errMsg);
        }
        if (exception instanceof ConstraintViolationException) {
            ConstraintViolationException constraintViolationException = (ConstraintViolationException) exception;
            Set<ConstraintViolation<?>> constraintViolations = constraintViolationException.getConstraintViolations();
            String constraintViolationsMsg = constraintViolations.stream()
                    .map(ConstraintViolation::getMessage)
                    .filter(Objects::nonNull)
                    .collect(Collectors.joining(", "));
            errMsg = StrUtil.format(
                    "第{}行数据校验异常: {}", context.readRowHolder().getRowIndex() + 1, constraintViolationsMsg);
            log.error(errMsg);
        }
        excelResult.getErrorList().add(errMsg);
        throw exception;
    }

    public ExcelResult<T> getExcelResult() {
        return excelResult;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {}
}
